<?php

namespace App\Trip\Plane\Requests;

use App\Models\Plane\PlaneOrders\PlaneOrder;
use Carbon\Carbon;
use Exception;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;

class RulesRequest implements Arrayable
{


    private Request|array $req;

    /**
     *
     */
    public function __construct(Request|array $request)
    {
        $this->req = $request;
    }

    public function getDiscount()
    {
        return $this->req['discount'] ?? '';
    }

    public function getFromCode()
    {
        return $this->req['from_code'] ?? '';
    }

    public function getToCode()
    {
        return $this->req['to_code'] ?? '';
    }

    public function getTripDate()
    {
        return $this->req['depart_date'];
    }

    /**
     * @throws Exception
     */
    public function getTripAt()
    {
        $date = $this->req['depart_date'];
        if (!Carbon::hasFormat($date, 'Y-m-d H:i')) {
            throw new Exception("格式错误");
        }
        return $date;
    }

    public function getCarrierCode()
    {
        return $this->getFlightNo() ?: $this->req['carrier_code'];
    }

    public function getFlightNo()
    {
        return $this->req['flight_no'] ?? '';
    }

    public function getCabin(): string
    {
        return strtoupper($this->req['cabin']);
    }

    /**
     * 1 成人 3 儿童
     * @return int
     */
    public function getPassengerType(): int
    {
        return $this->req['passenger_type'] ?? 1;
    }

    /**
     * 结算价 成人|儿童 用于计算退改规则的价格
     * @return array
     */
    public function getCheckPrices(): array
    {
        return $this->req['check_prices'] ?? [];
    }

    public function toArray(): array
    {
        if (is_array($this->req)) {
            return $this->req;
        }
        return $this->req->toArray();
    }

    /**
     *  1 退款规则 2 改签规则 4 行李规则 (3:退改,7:退改行李)
     * @return int
     */
    public function getRuleType()
    {
        return $this->req['rule_type'] ?? 7;
    }

    public function getOrderInfo(): ?PlaneOrder
    {
        return $this->req['order_info'] ?? null;
    }

    public function getOrderPassengers()
    {
        return $this->req['passengers'] ?? [];
    }

    public function getSubOutOrderIds(): array
    {
        return $this->req['sub_out_order_ids'] ?? [];
    }

    /**
     * @throws Exception
     */
    public function __get(string $name)
    {
        if (!isset($this->req[$name])) {
            throw new Exception("{$name} error");
        }
        return $this->req[$name];
    }
}